package com.witmore.neutron.ai.web.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jk.common.utils.LocalDateUtils;
import com.witmore.neutron.ai.api.dto.ContentDTO;
import com.witmore.neutron.ai.api.dto.MessageContentDTO;
import com.witmore.neutron.ai.db.entity.AgentDO;
import com.witmore.neutron.ai.db.entity.AgentSessionRecordDO;
import com.witmore.neutron.ai.db.entity.AgentSessionRecordDetailDO;
import com.witmore.neutron.ai.db.mapper.AgentSessionRecordDetailMapper;
import com.witmore.neutron.ai.db.mapper.AgentSessionRecordMapper;
import com.witmore.neutron.ai.web.controller.bo.MessageBO;
import com.witmore.neutron.ai.web.controller.vo.ChatRecordQuery;
import com.witmore.neutron.ai.web.enums.ShowFlagEnum;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.service.SessionRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * Description: SessionRecordServiceImpl
 * Author: 豆子高
 * Date: 2025/6/5 16:16
 */
@Service
public class SessionRecordServiceImpl implements SessionRecordService {

    @Autowired
    private AgentSessionRecordMapper agentSessionRecordMapper;

    @Autowired
    private AgentSessionRecordDetailMapper agentSessionRecordDetailMapper;

    @Override
    public AgentSessionRecordDO saveSessionRecord(MessageBO messageBO, AgentDO agentDO) {
        // 先查询是否有该会话  全局唯一
        AgentSessionRecordDO agentSessionRecordDO = agentSessionRecordMapper.selectOne(new LambdaQueryWrapper<AgentSessionRecordDO>()
                .eq(AgentSessionRecordDO::getSessionId, messageBO.getSessionId()));
        if (agentSessionRecordDO == null) {
            // 如果没有，则创建新的会话记录
            agentSessionRecordDO = new AgentSessionRecordDO();
            agentSessionRecordDO.setUserId(messageBO.getUserId());
            agentSessionRecordDO.setAgentId(agentDO.getId());
            agentSessionRecordDO.setAgentCode(agentDO.getAgentCode());
            agentSessionRecordDO.setAgentName(agentDO.getAgentName());
            agentSessionRecordDO.setSource(messageBO.getSource());
            agentSessionRecordDO.setSessionId(messageBO.getSessionId());
            agentSessionRecordDO.setFirstCompletion(this.getFirstCompletion(messageBO.getMessages()));
            agentSessionRecordDO.setRecordCount(1);
            agentSessionRecordDO.setUpdateTime(LocalDateTime.now());
            agentSessionRecordDO.setCreateTime(LocalDateTime.now());
            agentSessionRecordMapper.insert(agentSessionRecordDO);
        } else {
            // 如果有，则更新会话记录 TODO
            agentSessionRecordDO.setRecordCount(agentSessionRecordDO.getRecordCount() + 1);
            agentSessionRecordDO.setUpdateTime(LocalDateTime.now());
            agentSessionRecordMapper.updateById(agentSessionRecordDO);
        }
        return agentSessionRecordDO;
    }

    private String getFirstCompletion(List<MessageContentDTO> messages) {
        if (messages == null || messages.isEmpty()) {
            throw new IllegalArgumentException("消息内容不能为空");
        }
        // 首先过滤出 MessageContentVO 中 role为user的第一条消息
        String firstUserMsg = messages.stream()
                .filter(message -> "user".equalsIgnoreCase(message.getRole()))
                .findFirst()
                .map(MessageContentDTO::getContent)
                .orElse(null);
        List<ContentDTO> contentBOS = JSONArray.parseArray(firstUserMsg, ContentDTO.class);
        ;
        // 过滤出 contentBOS中 type= text 的那条消息
        if (contentBOS != null) {
            return contentBOS.stream()
                    .filter(content -> "text".equalsIgnoreCase(content.getType()))
                    .map(ContentDTO::getText)
                    .findFirst()
                    .orElse("（用户未提供输入）");
        }
        throw new IllegalArgumentException("消息内容不能为空");
    }

    @Override
    public Page<AgentSessionRecordDO> getRecordListPage(ChatRecordQuery query) {
        // 时间格式化
        LocalDateTime localDateTimeStart = null;
        LocalDateTime localDateTimeEnd = null;
        if (StringUtils.isNotEmpty(query.getStartTime()) && StringUtils.isNotEmpty(query.getEndTime())) {
            LocalDate localDateStart = LocalDateUtils.stringConvertDate(query.getStartTime());
            LocalDate localDateEnd = LocalDateUtils.stringConvertDate(query.getEndTime());
            // 如果开始时间大于结束时间，则抛出异常
            if (localDateStart.isAfter(localDateEnd)) {
                throw new IllegalArgumentException("开始时间不能大于结束时间");
            }
            localDateTimeStart = localDateStart.atTime(0, 0, 0);
            localDateTimeEnd = localDateEnd.atTime(23, 59, 59);
        }
        LambdaQueryWrapper<AgentSessionRecordDO> queryWrapper = new LambdaQueryWrapper<AgentSessionRecordDO>()
                .eq(AgentSessionRecordDO::getIsDeleted, 0)
                .eq(AgentSessionRecordDO::getUserId, GlobalAccountSession.getUserInfo().getId())
                .eq(StringUtils.isNotEmpty(query.getAgentCode()), AgentSessionRecordDO::getAgentCode, query.getAgentCode())
                .eq(query.getAgentId() != null, AgentSessionRecordDO::getAgentId, query.getAgentId())
                .eq(StringUtils.isNotEmpty(query.getSource()), AgentSessionRecordDO::getSource, query.getSource())
                .like(StringUtils.isNotEmpty(query.getSessionId()), AgentSessionRecordDO::getSessionId, query.getSessionId())
                .like(StringUtils.isNotEmpty(query.getKeyWord()), AgentSessionRecordDO::getFirstCompletion, query.getKeyWord())
                .between(localDateTimeStart != null,
                        AgentSessionRecordDO::getCreateTime, localDateTimeStart, localDateTimeEnd)
                .orderByDesc(AgentSessionRecordDO::getUpdateTime);
        Page<AgentSessionRecordDO> agentSessionRecordDOPage = agentSessionRecordMapper.selectPage(
                new Page<>(query.getPage(), query.getSize()),
                queryWrapper
        );
        if (agentSessionRecordDOPage == null || agentSessionRecordDOPage.getRecords() == null) {
            return new Page<>();
        }
        return agentSessionRecordDOPage;
    }

    @Override
    public Page<AgentSessionRecordDetailDO> getRecordDetailListPage(ChatRecordQuery query) {
        if (query == null || StringUtils.isEmpty(query.getSessionId())) {
            return new Page<>();
        }
        Page<AgentSessionRecordDetailDO> sessionRecordDetailDOPage = agentSessionRecordDetailMapper.selectPage(new Page<>(query.getPage(), query.getSize()),
                new LambdaQueryWrapper<AgentSessionRecordDetailDO>()
                        .eq(AgentSessionRecordDetailDO::getSessionId, query.getSessionId())
                        .eq(AgentSessionRecordDetailDO::getIsDeleted, 0)
                        .eq(AgentSessionRecordDetailDO::getShowFlag, ShowFlagEnum.SHOW.getCode())
        );
        if (sessionRecordDetailDOPage != null && sessionRecordDetailDOPage.getRecords() != null) {
            return sessionRecordDetailDOPage;
        }
        return new Page<>();
    }

}
